<template>
  <div class="back">
    <ElButton type="text" @click="router.push('/')">
      <el-icon><HomeFilled /></el-icon>
      返回首页
    </ElButton>
  </div>
  <div class="main">
    <div>
      <el-card>
        <template #header>
          <div>{{ title }}</div>
        </template>
        <div>
          <el-form>
            <el-form-item>
              <el-input v-model="formdata.username" placeholder="登录名" autofocus>
                <template #prefix>
                  <el-icon><UserFilled /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-input v-model="formdata.password" show-password placeholder="密码">
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="btns">
            <el-button type="danger">
              重置
              <el-icon><Close /></el-icon>
            </el-button>
            <el-button type="primary" @click="login">
              登录
              <el-icon><Check /></el-icon>
            </el-button>
            <el-button type="text" @click="router.push('/user/reg')">注册</el-button>
          </div>
        </template>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElButton, ElCard, ElForm, ElFormItem, ElInput, ElMessage } from 'element-plus'
import { ApiService } from '../../ts/ApiService'
import { BaseDataResult } from '../../ts/types/BaseResult'
import { UserInfo } from '../../ts/types/User'
import { useRouter } from 'vue-router'
import store from '../../store/index'
import { log } from '../../ts/logger'

const { updateUserInfo } = store()
const router = useRouter()

const title = ref('用户登录')
const formdata = ref({
  username: '',
  password: '',
})

const login = () => {
  log.debug('表单信息：', formdata.value)
  ApiService.post('/auth', formdata.value, (data: BaseDataResult<UserInfo>) => {
    log.debug('登录结果：', data)
    if (data.success) {
      updateUserInfo(true, data.data)
      router.push('/user/main')
    } else {
      ElMessage.error(data.message)
    }
  })
}
</script>
<style lang="scss" scoped>
.back {
  padding: 1rem;
  position: fixed;
  z-index: 2;
  top: 0px;
  right: 0px;
}
.main {
  width: 100vw;
  height: 100vh;
  > div {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.btns {
  text-align: end;
}
</style>
